package cn.sptpc.service.impl;

import cn.hutool.core.util.PageUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.sptpc.dao.UserDao;
import cn.sptpc.dao.impl.UserDaoI;
import cn.sptpc.entity.java.User;
import cn.sptpc.entity.web.JMsgEntity;
import cn.sptpc.entity.web.JLoginEntity;
import cn.sptpc.entity.web.JUserAllEntity;
import cn.sptpc.service.UserService;
import cn.sptpc.utils.FileUtils;
import com.google.gson.Gson;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.List;

public class UserServiceI implements UserService {
    private UserDao userDao = new UserDaoI();

    /**
     * 登录
     *
     * @return
     */
    @Override
    public String verifyUserLogin(HttpServletRequest request) {
        JLoginEntity entity = new JLoginEntity();
        Gson gson = new Gson();
        String verify = (String) request.getSession().getAttribute("verify");
        if (verify.equals(request.getParameter("verify").toLowerCase())){
            User user = userDao.getUser(Integer.parseInt(request.getParameter("id")),DigestUtil.md5Hex(request.getParameter("password")));
            if (user.getUsername() != null){
                request.getSession().setAttribute("user",user);
                entity.setCode(200);
                System.out.println(gson.toJson(entity));
                return gson.toJson(entity);
            }else {
                entity.setCode(300);
                return gson.toJson(entity);
            }
        }else {
            entity.setCode(400);
            String s = gson.toJson(entity);
            JLoginEntity jLoginEntity = gson.fromJson(s, JLoginEntity.class);
            return s;
        }
    }

    /**
     * 获取个人信息
     *
     * @param request
     * @return
     */
    @Override
    public String getUserInfo(HttpServletRequest request) {
        User suser = (User) request.getSession().getAttribute("user");
        long id = suser.getId();
        User user = userDao.getUserById(id);
        request.getSession().setAttribute("user",user);
        Gson gson = new Gson();
        return gson.toJson(user);
    }

    /**
     * 获取指定用户的信息
     * @param id
     * @return
     */
    @Override
    public String getUserInfo(long id) {
        User user = userDao.getUserById(id);
        Gson gson = new Gson();
        return gson.toJson(user);
    }

    /**
     * 头像上传
     *
     * @param request
     * @return
     */
    @Override
    public String fileUpload(HttpServletRequest request) {
        JUserAllEntity entity = new JUserAllEntity();
        InputStream in = FileUtils.uploadFile(request);
        String s = FileUtils.saveCompressPic(in, "D:/OASystem/face");
        String temp = (String) request.getSession().getAttribute("temp");
        User user = null;
        if(temp.equals("self")){
            user = (User) request.getSession().getAttribute("user");
        }else {
            user = userDao.getUserById(Long.parseLong(temp));
        }

        String oldAvatar = user.getAvater();
        if (oldAvatar!= null){
            File f = new File("D:/OASystem/face/"+oldAvatar);
            f.delete();
        }
        user.setAvater(s);
        Integer i = userDao.updataUser(user);
        if (i == 1){
            entity.setCode(0);
            entity.setMsg("修改成功");
        }else {
            entity.setCode(0);
            entity.setMsg("修改成功");
        }
        Gson gson = new Gson();
        return gson.toJson(entity);
    }

    /**
     * 获取图片
     * @param request
     * @param response
     * @return
     */
    @Override
    public InputStream getUserFace(HttpServletRequest request, HttpServletResponse response) {
        response.reset();
        User user = null;
        if ("self".equals(request.getParameter("id"))){
            user = (User) request.getSession().getAttribute("user");
        }else {
            user = userDao.getUserById(Long.parseLong(request.getParameter("id")));
        }
        User userById = userDao.getUserById(user.getId());
        String avatar = userById.getAvater();
        response.addHeader("Content-Disposition", "attachment; filename="+avatar);
        try {
            OutputStream out=response.getOutputStream();
            FileUtils.downloadFile("D:/OASystem/face/",avatar,out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取所有用户
     * @param request
     * @return
     */
    @Override
    public String getAllUser(HttpServletRequest request) {
        Gson gson = new Gson();
        JUserAllEntity entity = new JUserAllEntity();
        int page = Integer.parseInt(request.getParameter("page"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        int[] pageUtils = PageUtil.transToStartEnd(page, limit);
        pageUtils[1] = limit;
        User user = (User) request.getSession().getAttribute("user");
        List<User> users = userDao.queryAllUser(pageUtils,user);
        if (users == null){
            entity.setCode(1);
            return gson.toJson(entity);
        }
        Integer count = null;
        if(0 == user.getPermissions()){
             count = userDao.queryCount();
        }else {
            count = users.size();
        }

        entity.setCode(0);
        entity.setCount(count);
        entity.setData(users);
        return gson.toJson(entity);
    }

    /**
     * 添加用户
     *
     * @param request
     * @return
     */
    @Override
    public String insertUser(HttpServletRequest request) {
        long id = Long.parseLong(request.getParameter("id"));
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        int department = Integer.parseInt(request.getParameter("department"));
        int group = Integer.parseInt(request.getParameter("group"));
        long permissions = Long.parseLong(request.getParameter("permissions"));
        long sex = Long.parseLong(request.getParameter("sex"));
        String phone = request.getParameter("phone");
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setPassword(DigestUtil.md5Hex(password));
        user.setDepartmentId(department);
        user.setGroupId(group);
        user.setPermissions(permissions);
        user.setSex(sex);
        JMsgEntity entity = new JMsgEntity();
        User userById = userDao.getUserById(id);
            Integer i = userDao.insetAUser(user);
            if (i.equals(1)){
                entity.setCode(0);
                entity.setMsg("添加成功！！！");
            }else {
                entity.setCode(1);
                entity.setMsg("未知错误请联系管理员！！！");
            }
        Gson gson = new Gson();
        return gson.toJson(entity);
    }

    /**
     * 验证Id
     * @param request
     * @return
     */
    @Override
    public String checkUserId(HttpServletRequest request) {
        long id = Long.parseLong(request.getParameter("id"));
        User user = userDao.getUserById(id);
        JMsgEntity entity = new JMsgEntity();
        if (user != null){
            entity.setCode(1);
            entity.setMsg("用户已经存在！");
        }else {
            entity.setCode(0);
        }
        Gson gson = new Gson();
        return gson.toJson(entity);
    }

    /**
     * 查询用户
     *
     * @param request
     * @return
     */
    @Override
    public String queryUser(HttpServletRequest request) {
        Gson gson = new Gson();
        JUserAllEntity entity = new JUserAllEntity();
        String key = request.getParameter("key");
        User user = (User) request.getSession().getAttribute("user");
        List<User> users = userDao.queryUser(key,user);
        if (users.size() < 1){
            entity.setCode(1);
            entity.setMsg("未找到该用户！");
            return gson.toJson(entity);
        }
        entity.setCode(0);
        entity.setCount(users.size());
        entity.setData(users);
        System.out.println(gson.toJson(entity));
        return gson.toJson(entity);
    }

    /**
     * 删除用户
     *
     * @param request
     * @return
     */
    @Override
    public String deleteUser(HttpServletRequest request) {
        int id = Integer.parseInt(request.getParameter("id"));
        Integer i = userDao.deleteUser(id);
        JUserAllEntity entity = new JUserAllEntity();
        Gson gson = new Gson();
        if (i != null){
            entity.setCode(0);
            entity.setMsg("删除成功");
            return gson.toJson(entity);
        }else {
            entity.setCode(1);
            entity.setMsg("删除失败");
        }

        return gson.toJson(entity);
    }

    public String updataUser(HttpServletRequest request){
        JMsgEntity entity = new JMsgEntity();
        User user = new User();
        String password = request.getParameter("password");
        if (password != null){
            password= DigestUtil.md5Hex(password);
        }
        String username = request.getParameter("username");
        Long department = Long.parseLong(request.getParameter("department"));
        Long group = Long.parseLong(request.getParameter("group"));
        String phone = request.getParameter("phone");
        Long id = Long.parseLong(request.getParameter("id"));
        user.setId(id);
        user.setDepartmentId(department);
        user.setGroupId(group);
        user.setPassword(password);
        user.setPhone(phone);
        user.setUsername(username);
        Integer i = userDao.updataAUser(user);
        if (i == 1){
            entity.setCode(0);
            entity.setMsg("修改成功E");
        }else {
            entity.setCode(0);
            entity.setMsg("修改失败");
        }
        return new Gson().toJson(entity);
    }
}
